package com.ywb.filter;

import org.springframework.http.HttpRequest;
import org.springframework.http.client.support.HttpRequestWrapper;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@WebFilter("/*") //拦截所有资源
public class EncodingFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //基于HTTP
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //处理Post请求
        request.setCharacterEncoding("UTF-8");

        //处理Get请求
        String method = request.getMethod();
        if(method.equalsIgnoreCase("GET")){
            String serverInfo = request.getServletContext().getServerInfo();
            String version = serverInfo.substring(serverInfo.lastIndexOf("/") + 1, serverInfo.indexOf("."));
            if(version != null && Integer.parseInt(version) < 8) { //如果version的版本小于8的话
                //关键步骤
                MyWrapper wrapper = new MyWrapper(request);
                filterChain.doFilter(request, response);
            }
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }

    class MyWrapper extends HttpServletRequestWrapper {
        private HttpServletRequest request;

        /**
         * 获得需要处理的request对象
         * @param request
         */
        public MyWrapper(HttpServletRequest request) {
            super(request);
            this.request = request;
        }

        /**
         * 处理request的每个参数
         * @param name
         * @return
         */
        @Override
        public String getParameter(String name) {
            String value = request.getParameter(name);
            if(!StringUtils.hasLength(value)){
                return value;
            }
            try{
                //Tomcat7以下GET转码的核心点
                //使用new String(xx.getBytes("ISO-8859-1"), "UTF-8") 来转换字符编码
                value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            return value;
        }
    }
}
